<template>
	<view class="address-management-page">
		<!-- 顶部紫色渐变背景 -->
		<view class="top-bg">
			<view class="bg-shape bg-shape-1"></view>
			<view class="bg-shape bg-shape-2"></view>
			<view class="bg-shape bg-shape-3"></view>
		</view>

		<!-- 返回按钮 -->
		<view class="back-btn" @click="goBack">
			<image class="back-icon" src="/static/icons/back.png" mode="aspectFit"></image>
		</view>

		<scroll-view class="content" scroll-y @refresherrefresh="onRefresh" refresher-enabled
			:refresher-triggered="refreshing">
			<!-- 页面标题 -->
			<view class="page-header">
				<view class="header-content">
					<text class="page-title">地址管理</text>
					<text class="page-subtitle">共 {{ addressCount }} 个地址</text>
				</view>
			</view>

			<!-- 添加地址按钮 -->
			<view class="add-address-section">
				<button class="add-address-btn" @click="openAddAddressModal">
					<text class="add-icon">+</text>
					<text class="add-text">添加新地址</text>
				</button>
			</view>

			<!-- 地址列表 -->
			<view class="addresses-section">
				<view v-if="loading" class="loading-state">
					<view class="loading-spinner"></view>
					<text class="loading-text">加载地址中...</text>
				</view>

				<view v-else-if="!hasAddresses" class="empty-state">
					<view class="empty-icon">🏠</view>
					<text class="empty-title">暂无收货地址</text>
					<text class="empty-desc">请添加您的收货地址，方便商品配送</text>
					<button class="empty-action-btn" @click="openAddAddressModal">
						<text>添加地址</text>
					</button>
				</view>

				<view v-else class="addresses-list">
					<view v-for="address in addresses" :key="address.address_id" class="address-card"
						:class="{ 'default-address': address.is_default }">
						<view class="address-header">
							<view class="address-info">
								<text class="contact-name">{{ address.contact_name }}</text>
								<text class="contact-phone">{{ formatPhone(address.contact_phone) }}</text>
								<view v-if="address.is_default" class="default-tag">
									<text>默认</text>
								</view>
							</view>
							<view class="address-actions">
								<button class="action-btn edit" @click="editAddress(address)">编辑</button>
								<button class="action-btn delete"
									@click="confirmDeleteAddress(address.address_id)">删除</button>
							</view>
						</view>

						<view class="address-detail">
							<text class="detail-text">{{ address.address_detail }}</text>
						</view>

						<view class="address-footer">
							<text class="create-time">创建时间: {{ formatTime(address.created_at) }}</text>
							<view class="set-default" v-if="!address.is_default">
								<button class="set-default-btn"
									@click="setDefaultAddress(address.address_id)">设为默认</button>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 底部安全区域 -->
			<view class="bottom-space"></view>
		</scroll-view>

		<!-- 添加/编辑地址模态框 -->
		<view class="modal-mask" v-if="showAddressModal" @click="closeAddressModal">
			<view class="modal-content address-modal" @click.stop>
				<view class="modal-header">
					<text class="modal-title">{{ isEditing ? '编辑地址' : '添加地址' }}</text>
					<text class="modal-close" @click="closeAddressModal">×</text>
				</view>
				<view class="modal-body">
					<view class="form-item">
						<text class="form-label">联系人</text>
						<input class="form-input" v-model="addressForm.contact_name" placeholder="请输入联系人姓名"
							maxlength="20" />
						<text class="input-counter">{{ addressForm.contact_name.length }}/20</text>
					</view>
					<view class="form-item">
						<text class="form-label">手机号</text>
						<input class="form-input" v-model="addressForm.contact_phone" placeholder="请输入11位手机号"
							type="number" maxlength="11" />
					</view>
					<view class="form-item">
						<text class="form-label">详细地址</text>
						<textarea class="form-textarea" v-model="addressForm.address_detail" placeholder="请输入详细收货地址"
							maxlength="200" />
						<text class="textarea-counter">{{ addressForm.address_detail.length }}/200</text>
					</view>
					<view class="form-item">
						<view class="checkbox-item">
							<checkbox :checked="addressForm.is_default" color="#8A2BE2"
								@click="addressForm.is_default = !addressForm.is_default" />
							<text class="checkbox-label">设为默认地址</text>
						</view>
						<text class="checkbox-desc" v-if="hasAddresses && !isEditing">设置后将会取消当前的默认地址</text>
					</view>
				</view>
				<view class="modal-footer">
					<button class="modal-button cancel" @click="closeAddressModal">取消</button>
					<button class="modal-button confirm" @click="saveAddress" :disabled="savingAddress || !formValid">
						{{ savingAddress ? '保存中...' : '确认保存' }}
					</button>
				</view>
			</view>
		</view>

		<!-- 加载遮罩 -->
		<view class="loading-mask" v-if="globalLoading">
			<view class="loading-spinner large"></view>
			<text class="loading-text">处理中...</text>
		</view>
	</view>
</template>

<script>
	const API_BASE_URL = 'http://localhost:8000/api/v1';

	export default {
		name: 'AddressManagement',
		data() {
			return {
				loading: false,
				globalLoading: false,
				refreshing: false,
				savingAddress: false,
				hasAddresses: false,
				addressCount: 0,
				addresses: [],
				showAddressModal: false,
				isEditing: false,
				editingAddressId: null,
				addressForm: {
					contact_name: '',
					contact_phone: '',
					address_detail: '',
					is_default: false
				}
			};
		},
		computed: {
			token() {
				return uni.getStorageSync('token');
			},
			formValid() {
				return this.addressForm.contact_name.trim() &&
					this.addressForm.contact_phone.trim() &&
					this.addressForm.address_detail.trim() &&
					this.addressForm.contact_phone.match(/^1[3-9]\d{9}$/);
			}
		},
		onLoad() {
			this.loadAddresses();
		},
		onPullDownRefresh() {
			this.onRefresh();
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},

			// 下拉刷新
			async onRefresh() {
				this.refreshing = true;
				await this.loadAddresses();
				setTimeout(() => {
					this.refreshing = false;
				}, 500);
			},

			// 加载地址列表
			async loadAddresses() {
				this.loading = true;
				try {
					const [error, response] = await new Promise((resolve) => {
						uni.request({
							url: `${API_BASE_URL}/users/addresses`,
							method: 'GET',
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							success: (res) => resolve([null, res]),
							fail: (err) => resolve([err, null])
						});
					});

					if (error) {
						throw error;
					}

					if (response.statusCode === 200) {
						const data = response.data;
						this.hasAddresses = data.has_addresses;
						this.addressCount = data.address_count || 0;
						this.addresses = data.addresses || [];
						console.log('地址列表加载成功:', this.addresses);
					} else {
						throw new Error(response.data.detail || '获取地址失败');
					}
				} catch (error) {
					console.error('加载地址失败:', error);
					this.showError('加载地址失败');
				} finally {
					this.loading = false;
					uni.stopPullDownRefresh();
				}
			},

			// 打开添加地址模态框
			openAddAddressModal() {
				this.isEditing = false;
				this.editingAddressId = null;
				this.resetAddressForm();
				// 如果没有地址，默认设置为默认地址
				if (!this.hasAddresses) {
					this.addressForm.is_default = true;
				}
				this.showAddressModal = true;
			},

			// 编辑地址
			editAddress(address) {
				this.isEditing = true;
				this.editingAddressId = address.address_id;
				this.addressForm = {
					contact_name: address.contact_name,
					contact_phone: address.contact_phone,
					address_detail: address.address_detail,
					is_default: address.is_default
				};
				this.showAddressModal = true;
			},

			// 关闭地址模态框
			closeAddressModal() {
				this.showAddressModal = false;
				setTimeout(() => {
					this.resetAddressForm();
				}, 300);
			},

			// 重置地址表单
			resetAddressForm() {
				this.addressForm = {
					contact_name: '',
					contact_phone: '',
					address_detail: '',
					is_default: false
				};
			},

			// 保存地址
			async saveAddress() {
				if (!this.formValid) {
					this.showError('请填写完整的地址信息');
					return;
				}

				this.savingAddress = true;
				try {
					const url = this.isEditing ?
						`${API_BASE_URL}/users/address/${this.editingAddressId}` :
						`${API_BASE_URL}/users/address`;
					const method = this.isEditing ? 'PUT' : 'POST';

					const [error, response] = await new Promise((resolve) => {
						uni.request({
							url: url,
							method: method,
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							data: this.addressForm,
							success: (res) => resolve([null, res]),
							fail: (err) => resolve([err, null])
						});
					});

					if (error) {
						throw error;
					}

					if (response.statusCode === 200) {
						this.showSuccess(this.isEditing ? '地址更新成功' : '地址添加成功');
						this.closeAddressModal();
						await this.loadAddresses();
					} else {
						throw new Error(response.data.detail || '保存地址失败');
					}
				} catch (error) {
					console.error('保存地址失败:', error);
					this.showError(error.message || '保存地址失败');
				} finally {
					this.savingAddress = false;
				}
			},

			// 确认删除地址
			confirmDeleteAddress(addressId) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个地址吗？删除后无法恢复',
					confirmColor: '#FF4444',
					confirmText: '删除',
					cancelText: '取消',
					success: async (res) => {
						if (res.confirm) {
							await this.deleteAddress(addressId);
						}
					}
				});
			},

			// 删除地址
			async deleteAddress(addressId) {
				this.globalLoading = true;
				try {
					const [error, response] = await new Promise((resolve) => {
						uni.request({
							url: `${API_BASE_URL}/users/address/${addressId}`,
							method: 'DELETE',
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							success: (res) => resolve([null, res]),
							fail: (err) => resolve([err, null])
						});
					});

					if (error) {
						throw error;
					}

					if (response.statusCode === 200) {
						this.showSuccess('地址删除成功');
						await this.loadAddresses();
					} else {
						throw new Error(response.data.detail || '删除地址失败');
					}
				} catch (error) {
					console.error('删除地址失败:', error);
					this.showError(error.message || '删除地址失败');
				} finally {
					this.globalLoading = false;
				}
			},

			// 设为默认地址
			async setDefaultAddress(addressId) {
				this.globalLoading = true;
				try {
					const [error, response] = await new Promise((resolve) => {
						uni.request({
							url: `${API_BASE_URL}/users/addresses/${addressId}/set-default`,
							method: 'PUT',
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							success: (res) => resolve([null, res]),
							fail: (err) => resolve([err, null])
						});
					});

					if (error) {
						throw error;
					}

					if (response.statusCode === 200) {
						this.showSuccess('默认地址设置成功');
						await this.loadAddresses();
					} else {
						throw new Error(response.data.detail || '设置默认地址失败');
					}
				} catch (error) {
					console.error('设置默认地址失败:', error);
					this.showError(error.message || '设置默认地址失败');
				} finally {
					this.globalLoading = false;
				}
			},

			// 显示成功提示
			showSuccess(message) {
				uni.showToast({
					title: message,
					icon: 'success',
					duration: 2000
				});
			},

			// 显示错误提示
			showError(message) {
				uni.showToast({
					title: message,
					icon: 'none',
					duration: 3000
				});
			},

			// 格式化手机号
			formatPhone(phone) {
				if (!phone) return '';
				return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
			},

			// 格式化时间
			formatTime(timeString) {
				if (!timeString) return '';
				try {
					const date = new Date(timeString);
					const now = new Date();
					const diff = now - date;
					const days = Math.floor(diff / (1000 * 60 * 60 * 24));

					if (days === 0) {
						return '今天';
					} else if (days === 1) {
						return '昨天';
					} else if (days < 7) {
						return `${days}天前`;
					} else {
						return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
					}
				} catch (e) {
					return timeString;
				}
			}
		}
	};
</script>

<style scoped>
	.address-management-page {
		position: relative;
		min-height: 100vh;
		background: linear-gradient(180deg, #f9f7ff 0%, #f0ebff 100%);
	}

	.top-bg {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 300rpx;
		background: linear-gradient(135deg, #8A2BE2 0%, #9370DB 50%, #DA70D6 100%);
		z-index: 0;
		overflow: hidden;
	}

	.bg-shape {
		position: absolute;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.1);
	}

	.bg-shape-1 {
		width: 200rpx;
		height: 200rpx;
		top: -100rpx;
		right: -50rpx;
	}

	.bg-shape-2 {
		width: 150rpx;
		height: 150rpx;
		bottom: 30rpx;
		left: -60rpx;
	}

	.bg-shape-3 {
		width: 100rpx;
		height: 100rpx;
		top: 80rpx;
		left: 25%;
	}

	/* 返回按钮 */
	.back-btn {
		position: fixed;
		top: 80rpx;
		left: 30rpx;
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.9);
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
		z-index: 1000;
		backdrop-filter: blur(10px);
	}

	.back-icon {
		width: 32rpx;
		height: 32rpx;
	}

	.content {
		position: relative;
		z-index: 1;
		height: 100vh;
		padding: 30rpx 24rpx;
		box-sizing: border-box;
	}

	.page-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		padding-top: 40rpx;
	}

	.header-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: flex-end;
	}

	.page-title {
		font-size: 40rpx;
		font-weight: 700;
		color: #333;
		display: block;
		margin-bottom: 8rpx;
	}

	.page-subtitle {
		font-size: 26rpx;
		color: #666;
		display: block;
	}

	/* 添加地址按钮 */
	.add-address-section {
		margin-bottom: 30rpx;
	}

	.add-address-btn {
		width: 100%;
		padding: 28rpx;
		background: rgba(255, 255, 255, 0.9);
		border: 2rpx dashed #8A2BE2;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 16rpx;
		transition: all 0.3s ease;
	}

	.add-address-btn:active {
		transform: scale(0.98);
		background: rgba(138, 43, 226, 0.05);
	}

	.add-icon {
		font-size: 32rpx;
		color: #8A2BE2;
		font-weight: 300;
	}

	.add-text {
		font-size: 28rpx;
		color: #8A2BE2;
		font-weight: 500;
	}

	/* 地址卡片样式 */
	.addresses-section {
		margin-bottom: 40rpx;
	}

	.address-card {
		background: rgba(255, 255, 255, 0.9);
		border-radius: 24rpx;
		padding: 32rpx;
		margin-bottom: 24rpx;
		backdrop-filter: blur(10px);
		box-shadow: 0 6rpx 24rpx rgba(138, 43, 226, 0.1);
		border: 1rpx solid rgba(255, 255, 255, 0.6);
		transition: all 0.3s ease;
	}

	.address-card:active {
		transform: translateY(-2rpx);
		box-shadow: 0 8rpx 32rpx rgba(138, 43, 226, 0.15);
	}

	.address-card.default-address {
		border: 2rpx solid #8A2BE2;
		background: rgba(138, 43, 226, 0.05);
	}

	.address-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.address-info {
		flex: 1;
		display: flex;
		align-items: center;
		gap: 20rpx;
		flex-wrap: wrap;
	}

	.contact-name {
		font-size: 30rpx;
		font-weight: 600;
		color: #333;
	}

	.contact-phone {
		font-size: 26rpx;
		color: #666;
	}

	.default-tag {
		padding: 6rpx 16rpx;
		background: linear-gradient(135deg, #8A2BE2, #9370DB);
		color: white;
		border-radius: 12rpx;
		font-size: 22rpx;
		font-weight: 500;
	}

	.address-actions {
		display: flex;
		gap: 16rpx;
	}

	.action-btn {
		padding: 8rpx 16rpx;
		border: none;
		border-radius: 8rpx;
		font-size: 22rpx;
		font-weight: 500;
		transition: all 0.2s ease;
	}

	.action-btn:active {
		transform: scale(0.95);
	}

	.action-btn.edit {
		background: #e3f2fd;
		color: #1976d2;
	}

	.action-btn.delete {
		background: #ffebee;
		color: #d32f2f;
	}

	.address-detail {
		margin-bottom: 20rpx;
	}

	.detail-text {
		font-size: 26rpx;
		color: #333;
		line-height: 1.4;
	}

	.address-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-top: 20rpx;
		border-top: 1rpx solid #f0f0f0;
	}

	.create-time {
		font-size: 22rpx;
		color: #999;
	}

	.set-default-btn {
		padding: 8rpx 16rpx;
		background: linear-gradient(135deg, #8A2BE2, #9370DB);
		color: white;
		border: none;
		border-radius: 8rpx;
		font-size: 22rpx;
		font-weight: 500;
		transition: all 0.2s ease;
	}

	.set-default-btn:active {
		transform: scale(0.95);
		opacity: 0.8;
	}

	/* 加载状态 */
	.loading-state,
	.empty-state {
		text-align: center;
		padding: 120rpx 0;
	}

	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 4rpx solid #f3f3f3;
		border-top: 4rpx solid #8A2BE2;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin: 0 auto 20rpx;
	}

	.loading-spinner.large {
		width: 80rpx;
		height: 80rpx;
		border-width: 6rpx;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.loading-text {
		font-size: 28rpx;
		color: #666;
	}

	.empty-icon {
		font-size: 80rpx;
		margin-bottom: 20rpx;
		display: block;
	}

	.empty-title {
		font-size: 32rpx;
		color: #333;
		display: block;
		margin-bottom: 12rpx;
		font-weight: 600;
	}

	.empty-desc {
		font-size: 26rpx;
		color: #888;
		line-height: 1.5;
		margin-bottom: 40rpx;
	}

	.empty-action-btn {
		padding: 20rpx 40rpx;
		background: linear-gradient(135deg, #8A2BE2, #9370DB);
		color: white;
		border: none;
		border-radius: 12rpx;
		font-size: 28rpx;
		font-weight: 500;
	}

	.empty-action-btn:active {
		transform: scale(0.98);
	}

	/* 模态框样式 */
	.modal-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 2000;
		padding: 40rpx;
		animation: fadeIn 0.3s ease;
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
		}

		to {
			opacity: 1;
		}
	}

	.modal-content {
		background: white;
		border-radius: 24rpx;
		width: 100%;
		max-width: 600rpx;
		max-height: 80vh;
		overflow: hidden;
		box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.2);
		animation: slideUp 0.3s ease;
	}

	@keyframes slideUp {
		from {
			transform: translateY(50rpx);
			opacity: 0;
		}

		to {
			transform: translateY(0);
			opacity: 1;
		}
	}

	.address-modal {
		max-width: 560rpx;
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 40rpx 32rpx 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
		flex-shrink: 0;
	}

	.modal-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.modal-close {
		font-size: 40rpx;
		color: #999;
		padding: 10rpx;
	}

	.modal-body {
		padding: 32rpx;
		flex: 1;
		overflow-y: auto;
		max-height: 60vh;
	}

	.form-item {
		margin-bottom: 32rpx;
		position: relative;
	}

	.form-label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
		font-weight: 500;
	}

	.form-input {
		width: 100%;
		padding: 24rpx;
		border: 1rpx solid #e0e0e0;
		border-radius: 12rpx;
		font-size: 28rpx;
		background: #f9f9f9;
		transition: border-color 0.3s ease;
	}

	.form-input:focus {
		border-color: #8A2BE2;
		background: white;
	}

	.form-textarea {
		width: 100%;
		height: 160rpx;
		padding: 24rpx;
		border: 1rpx solid #e0e0e0;
		border-radius: 12rpx;
		font-size: 28rpx;
		background: #f9f9f9;
		transition: border-color 0.3s ease;
	}

	.form-textarea:focus {
		border-color: #8A2BE2;
		background: white;
	}

	.input-counter,
	.textarea-counter {
		display: block;
		text-align: right;
		font-size: 24rpx;
		color: #999;
		margin-top: 8rpx;
	}

	.checkbox-item {
		display: flex;
		align-items: center;
		gap: 16rpx;
		margin-bottom: 8rpx;
	}

	.checkbox-label {
		font-size: 26rpx;
		color: #333;
		font-weight: 500;
	}

	.checkbox-desc {
		font-size: 24rpx;
		color: #999;
		display: block;
		margin-left: 52rpx;
	}

	.modal-footer {
		display: flex;
		padding: 0 32rpx 32rpx;
		gap: 20rpx;
		flex-shrink: 0;
	}

	.modal-button {
		flex: 1;
		padding: 24rpx;
		border: none;
		border-radius: 12rpx;
		font-size: 28rpx;
		font-weight: 500;
		transition: all 0.2s ease;
	}

	.modal-button:active {
		transform: scale(0.98);
	}

	.modal-button.cancel {
		background: #f5f5f5;
		color: #666;
	}

	.modal-button.confirm {
		background: linear-gradient(135deg, #8A2BE2, #9370DB);
		color: white;
	}

	.modal-button:disabled {
		background: #ccc;
		color: #999;
		transform: none;
	}

	/* 全局加载遮罩 */
	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(255, 255, 255, 0.9);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		z-index: 3000;
	}

	.bottom-space {
		height: 40rpx;
	}
</style>